package org.lex.keytool.core;

import java.util.HashMap;
import java.util.Map;

/**
 * X.509 Distinguished Names
 */
public class DName implements Cloneable {
	public enum Name {
		CN("Common Name"), OU("Organization Unit"), O("Organization Name"), L("Locality Name"), S("State Name"), C(
				"Country");

		public String getDescription() {
			return description;
		}

		private String description = null;

		private Name(String description) {
			this.description = description;
		}
	}

	private Map<Name, String> map = new HashMap<Name, String>();

	public String get(Name name) {
		return map.get(name);
	}

	public void set(Name name, String value) {
		if (-1 != value.indexOf(',')) {
			value = value.replace(",", "\\,");
		}
		map.put(name, value);
	}

	public DName clone() {
		try {
			return (DName) super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
			return null;
		}
	}

	public String toString() {
		StringBuilder buf = new StringBuilder();
		boolean first = true;
		Name[] keys = { Name.CN, Name.OU, Name.O, Name.L, Name.S, Name.C };
		for (Name key : keys) {
			String value = map.get(key);
			if (null != value) {
				if (false == first) {
					buf.append(", ");
				} else {
					first = false;
				}
				buf.append(key.name()).append('=').append(value);
			}
		}
		return buf.toString();
	}
}
